<template>
    <div id="app">
        <div class="main">
            <!-- 头部 -->
            <div class="header">
                <!-- 公司应用名称 -->
                <div class="title">
                    <a :href="config.home" target="_blank">{{
                        config.title
                    }}</a>
                </div>
                <!-- 用户名称 -->
                <div class="username" v-html="config.user"></div>
            </div>
            <!-- 左侧 -->
            <div class="left">
                <!-- 聊天内容 -->
                <div class="content chatMessage" id="content">
                    <template v-for="(item, index) in chats">
                        <div :class="item.type">
                            <div
                                v-html="item.content"
                                :class="{ message: item.message }"
                            ></div>
                        </div>
                    </template>
                    <div class="clearfix" id="end_content"></div>
                </div>
                <!-- 聊天输入框 -->
                <div class="save">
                    <!-- 小工具 -->
                    <div class="tools">
                        <!-- emoji -->
                        <span class="tools-btn" title="选择表情" id="emoji-btn">
                            <i class="iconfont icon-emoji"></i>
                        </span>
                        <!-- link -->
                        <span
                            class="tools-btn"
                            title="网址链接"
                            id="link-btn"
                            @click="showLinkDialog"
                        >
                            <i class="iconfont icon-link"></i>
                        </span>
                        <!-- file -->
                        <span
                            class="tools-btn"
                            title="发送文件"
                            id="upload-btn"
                            v-if="config.uploadLink"
                        >
                            <i class="iconfont icon-filepackage"></i>
                        </span>
                    </div>
                    <!-- 输入框 -->
                    <div class="text">
                        <textarea
                            id="text-input"
                            placeholder="请输入要发送的消息..."
                            v-model="content"
                        ></textarea>
                    </div>
                    <!-- 发送框 -->
                    <div class="footer">
                        <span class="chat-btn close" @click="onClose">
                            关闭(<u>C</u>)
                        </span>
                        <span class="chat-btn send" id="send" @click="send">
                            发送(<u>S</u>)
                        </span>
                    </div>

                    <!-- 表情包选择框 -->
                    <div id="emoji"></div>
                </div>
            </div>
            <!-- 右侧 -->
            <div class="right">
                <!-- 应用logo信息 -->
                <div class="logo">
                    <img :src="config.logo" :alt="config.title" />
                </div>
                <p class="welcome" v-html="config.wellcome"></p>
            </div>
        </div>
        <!-- 链接弹窗 -->
        <mDialog
            v-model="showLink"
            type="links"
            @ok="linkSuccess"
            @cancel="linkCancel"
        ></mDialog>
        <!-- 提示弹窗 -->
        <mDialog v-model="showAlert" :msg="alertMsg" @ok="alertClose"></mDialog>
        <!-- 断开连接提示弹窗 -->
        <mDialog
            v-model="showClose"
            type="confirm"
            msg="确认要结束关闭会话么？"
            @ok="close"
            @cancel="showClose = false"
        ></mDialog>
    </div>
</template>

<script>
import Util from "common/util";
import chatMixins from "common/mixins/chat/index";
import { MonDialog as mDialog } from "mon-util";
import Api from "page/api";
export default {
    name: "clientChat",
    mixins: [chatMixins],
    components: {
        mDialog,
    },
    data() {
        return {
            // 配置信息
            config: window.config,
        };
    },
    // 初始化
    mounted: function () {
        // 设置页面标题
        Util.documentTitle(this.config.title);
        // 初始化表情包
        this._initEmoji();
        // 初始化文件上传
        if (this.config.uploadLink) {
            this._initUpload();
        }
        // 拉倒底部
        this._contentToBottom();
        // 从缓存中获取chatConfig
        this.chatConfig.uid = Util.getStorage("chat_uid", null, false);
        this.chatConfig.group = Util.getStorage("chat_group", null, false);
        // 初始化websocket
        this._initWebsocket();
    },
    methods: {
        // 初始化websocket链接
        _initWebsocket() {
            // 初始化websocket
            if (window.WebSocket) {
            } else if (window.MozWebSocket) {
                window.WebSocket = MozWebSocket;
            } else {
                this.showAlertDialog(
                    "您正在使用过时的浏览器，是时候更换一个更好的浏览器来提升用户体验！"
                );
                return;
            }
            this.ws = new WebSocket(this.config.server);
            this.ws.onopen = () => {
                let data = {
                    cmd: this.config.cmd,
                    type: "login",
                    app: this.config.app,
                    uid: this.chatConfig.uid || "",
                    group: this.chatConfig.group || "",
                };
                this.ws.send(JSON.stringify(data));
                // 设置心跳
                setInterval(() => {
                    this.ws.send(
                        JSON.stringify({
                            cmd: this.config.cmd,
                            type: "ping",
                        })
                    );
                }, 50000);
            };
            this.ws.onmessage = (e) => {
                let res = JSON.parse(e.data);
                if (res.code == "200") {
                    let data = res.data;
                    switch (data.type) {
                        case "chat":
                            // 记录用户ID及组别ID
                            this.chatConfig.uid = data.uid;
                            this.chatConfig.group = data.group;
                            // 缓存数据
                            Util.setStorage("chat_uid", data.uid);
                            Util.setStorage("chat_group", data.group);
                            if (data.msg) {
                                let temp = chatMessage.parse("tips", {
                                    content: data.msg,
                                });
                                this.chats.push({
                                    type: "tips",
                                    message: false,
                                    content: temp,
                                });
                            }
                            // 拉取聊天记录
                            Api.pull(
                                this.config.app,
                                data.uid,
                                data.group
                            ).then((result) => {
                                let res = result.data;
                                if (res.length > 0) {
                                    this.initList(res, data.msg);
                                }
                            });

                            break;
                        case "wait":
                            // 记录用户ID及组别ID
                            this.chatConfig.uid = data.uid;
                            // 缓存数据
                            Util.setStorage("chat_uid", data.uid);
                            let temp = chatMessage.parse("tips", {
                                content: data.msg,
                            });
                            this.chats.push({
                                type: "tips",
                                message: false,
                                content: temp,
                            });
                            break;
                        case "tips":
                        case "img":
                        case "text":
                        case "news":
                            let date = "";
                            if (data.time) {
                                date = Util.formatDate(data.time);
                            }

                            let send =
                                data.from == this.chatConfig.uid
                                    ? "ask"
                                    : "reply";
                            let sdk = chatMessage.setPath(
                                "/static/libs/monEmoji/img/"
                            );
                            let content = sdk.parse(
                                data.type,
                                data,
                                date,
                                send
                            );
                            this.chats.push({
                                type: send,
                                message: false,
                                content: content,
                            });

                            break;
                        case "receptionExit":
                            // 客服关闭聊天会话
                            let tmp = chatMessage.parse("tips", {
                                content: data.msg,
                            });
                            this.chats.push({
                                type: "tips",
                                message: false,
                                content: tmp,
                            });
                            this.ws.close();
                            this.ws = null;
                            break;
                    }
                }
            };
            this.ws.onerror = (event) => {
                console.log(event);
                this.showAlertDialog("链接客服中心异常，请稍后再试。");
            };
            this.ws.onclose = () => {
                let temp = chatMessage.parse("tips", {
                    content: "当前会话已结束",
                });
                this.chats.push({
                    type: "tips",
                    message: false,
                    content: temp,
                });
            };
        },
    },
};
</script>
<style>
#emoji {
    width: 320px;
    min-width: 320px;
    max-width: 640px;
    height: 146px;
    position: absolute;
    top: -152px;
    left: 2px;
    z-index: 999;
    border: 1px solid #eee;
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.1),
        inset 0 -1px 0 rgba(0, 0, 0, 0.07);
    border-radius: 4px;
    background: #fff;
    overflow-x: hidden;
    display: none;
}
</style>
